package com.william.xiaobujiantest.Tools;

import android.location.Location;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.william.xiaobujiantest.Whats;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static android.content.ContentValues.TAG;

/**
 * Created by william on 2017/5/8.
 */

public class ReceiveResponseThread extends Thread {

    private Handler handler;
    private Location location;

    public ReceiveResponseThread(Handler handler, Location location) {
        this.handler = handler;
        this.location = location;
    }

    private String getRealAPI(){
        return Whats.WEATHERAPI
                +"city="
                +this.location.getLongitude()
                +","
                +this.location.getLatitude()
                +"&key="
                +Whats.WEATHERKEY;
    }

    @Override
    public void run() {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(getRealAPI());
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            Log.e(TAG, "run: 获得天气数据："+response.toString() );
            Message message = Message.obtain();
            JSONObject jsonObject = new JSONObject(response.toString());
            message.obj = jsonObject;
            message.what = Whats.RECEIVE_RESPONSE;
            this.handler.sendMessage(message);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
